package test_goroutine

import (
	"fmt"
	"time"
)

func say(str string) {
	for i := 0; i < 5; i++ {
		time.Sleep(10 * time.Millisecond)
		fmt.Println(str)
	}
}

func testChannel(s []int, c chan int) {
	for _, v := range s {
		c <- v
	}
}

func rangeChannel(c chan int) {
	for {
		num, ok := <-c
		if !ok {
			close(c)
			break
		} else {
			fmt.Println(num)
		}
	}
}

func closeChannel(c chan int) {
	for i := range c {
		fmt.Println("range c : ", i)
	}

}

func Do() {
	fmt.Println("go并发测试")

	//测试并发
	go say("hello")
	say("world")

	//测试channel传递数据
	c := make(chan int)
	nums := []int{1, 2}
	go testChannel(nums, c)
	a, b := <-c, <-c
	fmt.Println(a + b)

	//带缓冲区的channel
	cc := make(chan int, 2)
	cc <- 3
	cc <- 4
	fmt.Println(<-cc + <-cc)

	//range遍历channel
	c1 := make(chan int, 11)
	for i := 0; i < 10; i++ {
		c1 <- i
	}
	go closeChannel(c1)

	//关闭channel
	go closeChannel(c)
	go closeChannel(cc)
	go closeChannel(c1)
}
